

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux'
import style from './style.module.css'
import { Select, Breadcrumb, message, Modal, TimePicker, Table, Form, Input, Button, Space, Switch } from 'antd'
import Pictures from '../../../components/Upload/index.jsx'
import axios from 'axios';

const SpikeConfig = (props) => {
    const [data, setData] = useState([])  //数据
    const [img, setImg] = useState({})  //图片的上传
    const [title, setTitle] = useState("")  //标题
    const [time, settime] = useState("")  //时间
    const [endTime, setendTime] = useState("") //结束时间
    const [state, setstate] = useState("") //状态
    const [id, setid] = useState("")  //id
    const [stateOpen, setstateOpen] = useState("") //状态

    const { Option } = Select;
    // 获取列表
    useEffect(() => {
        axios.get('/api/kill').then(res => {
            setData(res.data)
        })
    }, []);


    // 弹框的属性
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isModal, setIsModal] = useState(false)
    const showModal = () => {
        setIsModalVisible(true);
    };


    // 上传图片
    const handleImg = (e) => {
        console.log(e.response, '12');
        setImg(e.response)
    }
    // 加key函数
    const setKeyForList = (list) => {
        list.forEach(item => {
            item.key = item.id
        })
        return list
    }
    console.log(setKeyForList)
    // form表单里的数据  添加数据
    const onFinish = (value) => {
        setIsModalVisible(false);
        let arr = form.getFieldValue()
        console.log(arr, '00000--->');
        console.log(value);
        const flag = true;
        const rangeValue = value['time'];
        console.log('Success:', [rangeValue[0].format('hh:mm:ss'), rangeValue[1].format('hh:mm:ss')]);
        // 添加的接口
        axios({
            url: '/api/addkill',
            method: 'post',
            data: {
                title: value.title,
                time: rangeValue[0].format('hh:mm:ss'),
                endTime: rangeValue[1].format('hh:mm:ss'),
                state: value.state ? '1' : '0',
                img: img.imgUrl,
            }
        }).then(res => {
            axios.get('/api/kill').then(res => {
                setData(res.data)
            })
        })

    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    // 删除
    const handleDel = (id) => {
        axios.delete(`/api/delete/${id}`).then(res => {
            console.log(res);
            message.info('删除成功')
            axios.get('/api/kill').then(res => {
                setData(res.data)
            })
        })
    }
    // 编辑
    const handleEdit = (value) => {
        if (value.state == '1') {
            value.state = 0
        } else {
            value.state = 1
        }
        axios({
            url: '/api/killedit',
            method: 'put',
            data: {
                title: value.title,
                time: value.time,
                img: value.img,
                create_time: value.create_time,
                id: value.id,
                state: value.state,
                endTime: value.endTime,

            }
        }).then(res => {
            message.info('修改成功');
        })
    }
    // 搜索
    const handleSearch = (value) => {
        console.log(stateOpen, '111');
        axios({
            url: '/api/kill',
            method: 'get',
            params: {
                keyWord: value.target.defaultValue,
                state: stateOpen,
            }
        }).then(res => {
            setData(res.data)
            console.log(res);
        })
    }
    // 筛选开启还是关闭
    const handleoption = (state) => {
        console.log(state, '222');
        setstateOpen(state)
        axios.get('/api/kill', { params: { state: state } }).then(res => {
            setData(res.data)
        })
    }
    const handleAdd = () => {
        props.history.push('/layout/shop')
    }
    const [form] = Form.useForm();
    const [record, setRecord] = useState({})
    // 点击编辑 出现弹框
    const handleEditList = (value) => {
        console.log(value);
        // 打开弹框
        setIsModal(true)
        setTitle(value.title)
        setImg(value.img)
        setendTime(value.endTime)
        setid(value.id)
        setstate(value.state)
        settime(value.time)
    }
    // 点击确定
    const handleOk = () => {
        console.log(state, '123');
        // 编辑接口
        axios({
            url: '/api/killedit',
            method: 'put',
            data: {
                id,
                title,
                time,
                endTime,
                img,
                state,
            }
        }).then(res => {
            setIsModal(false)
            axios.get('/api/kill').then(res => {
                setData(res.data)
            })
            message.info('编辑成功')
        })

    };
    // 点击取消
    const handleCancel = () => {
        setIsModal(false);
    };
    const handleCancelAdd = () => {
        setIsModalVisible(false);
    }
    // 表头+数据
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: '130px',
            align: 'center',
        },
        {
            title: '秒杀名称',
            dataIndex: 'title',
            key: 'title',
            width: '170px',
            align: 'center',
        },
        {
            title: '秒杀时段',
            key: 'time',
            width: '170px',
            align: 'center',
            render: (text) => {
                return <>
                    {text.time}-{text.endTime}
                </>
            }
        },
        {
            title: '轮播图',
            key: 'img',
            dataIndex: 'img',
            width: '170px',
            align: 'center',
            render: (text, record) => (
                <div>
                    <img src={record.img} alt="" />
                </div>
            ),
        },
        {
            title: '状态',
            key: 'state',
            dataIndex: 'state',
            width: '170px',
            align: 'center',
            render: (text, record) => (
                <Switch onClick={() => handleEdit(record)} defaultChecked={record.state} checkedChildren="开启" unCheckedChildren="关闭" />
            ),
        },
        {
            title: '创建时间',
            key: 'create_time',
            dataIndex: 'create_time',
            width: '200px',
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            width: '200px',
            align: 'center',
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => {
                        handleEditList(record)
                        setRecord(record)
                    }}>编辑</a>
                    {/* <a onClick={() => handleEditList(record)}>编辑</a> */}
                    <a onClick={() => handleDel(record.id)}>删除</a>
                    <a onClick={() => handleAdd()}>添加商品</a>
                </Space>
            ),
        },
    ];



    return (
        // 内容
        <div className={style.SpikeConfigBox}>
            {/* 面包屑 */}
            <div className={style.SpikeConfigBoxHeader}>
                <Breadcrumb separator=">">
                    <Breadcrumb.Item>
                        <i className='iconfont icon-gengduo-2'></i>
                        <a href="/layout">主页</a>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        秒杀管理
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        秒杀配置
                    </Breadcrumb.Item>
                </Breadcrumb>
            </div>
            <div className={style.SpikeConfigBoxMain}>
                {/* 筛选+搜索 */}
                <div className={style.SpikeConfigBoxMainSearch}>
                    <div className={style.p}>
                        <b>是否显示</b>
                        <Select style={{ width: 120 }} onChange={handleoption}>
                            <Option value="1">开启 </Option>
                            <Option value="0">关闭</Option>
                        </Select>
                    </div>
                    <p>
                        <b>秒杀名称</b>
                        <Input placeholder=" 请输入商品名称，关键字，商品ID " onPressEnter={handleSearch} />
                    </p>
                </div>
                <Button type="primary" onClick={showModal}>添加秒杀配置</Button>
                {/* 编辑弹框 */}
                <Modal title="编辑" visible={isModal} onOk={handleOk} onCancel={handleCancel}>
                    <p>秒杀名称：<Input type='text' value={title} onChange={(e) => setTitle(e.target.value)}></Input></p>
                    <p>图片：<img src={img} alt="" /></p>
                    {/* <p>状态：<Switch defaultChecked={state} checkedChildren="开启" unCheckedChildren="关闭" /></p> */}

                </Modal>
                {/* 弹框 */}
                <Modal title="添加配置" footer={null} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                    <Form
                        form={form}
                        name="basic"
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        {/* 名称 */}
                        <Form.Item
                            label="名称"
                            name="title"
                        >
                            <Input value={title} onChange={(e) => setTitle(e.target.value)} />
                        </Form.Item>
                        <Form.Item name="time" label="时间范围" >
                            {/* 时间选择 */}
                            <TimePicker.RangePicker />
                        </Form.Item>
                        {/* 图片上传 */}
                        <Form.Item
                            name="img"
                            label="幻灯片"
                            valuePropName="fileList"
                        // getValueFromEvent={normFile}
                        >
                            <Pictures content={handleImg} />
                        </Form.Item>
                        {/* 状态 */}
                        <Form.Item name='state' label="状态" valuePropName="checked" checkedChildren="开启" unCheckedChildren="关闭">
                            <Switch />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button style={{ marginRight: '10px' }} onClick={() => handleCancelAdd()}>取消</Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>

                        </Form.Item>
                    </Form>
                </Modal>
                {/* 表格 */}
                <Table columns={columns} rowKey="id" dataSource={data} scroll={{ y: 460 }} />
            </div>
        </div>
    );
}
export default connect((state) => {
    return {

    }
})(SpikeConfig);
